package com.sgb.kjwl.view.ui.fragment.transport;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.sgb.capital.model.PayInfoEntity;
import com.sgb.capital.model.QRcodeEntity;
import com.sgb.capital.view.ui.activity.PersonPayActivity;
import com.sgb.capital.view.ui.activity.QrCodeActivity;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentTransportOrderDriverBinding;
import com.sgb.kjwl.model.entity.OrderEntity;
import com.sgb.kjwl.model.entity.transport.order.MyOrderEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.DialogHelper;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.activity.transport.OfflineCollectionConfirmActivity;
import com.sgb.kjwl.view.ui.activity.transport.PayQuotationOrderActivity;
import com.sgb.kjwl.view.ui.activity.transport.SureStartTransportActivity;
import com.sgb.kjwl.view.ui.activity.transport.driver.trans.ChoosePaymentTypeDialog;
import com.sgb.kjwl.view.ui.activity.transport.owner.TransportOrderDetailOwnerActivity;
import com.sgb.kjwl.view.ui.adapter.transport.order.TransportOrderDriverAdapter;
import com.sgb.kjwl.viewmodel.transport.TransportOrderDriverViewModel;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.event.EventConstant;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Time:
 * Author:熊丽
 * Description:司机运输订单
 */
public class TransportOrderDriverFragment extends AppLazyFragment implements TransportOrderDriverAdapter.OrderOnClickListener {
    TransportOrderDriverViewModel viewModel;

    private FragmentTransportOrderDriverBinding mBinding;
    private TransportOrderDriverAdapter mAdapter;
    Map mMap;
    private int tabposition = 0;
    private boolean isLodMore = false;

    public static TransportOrderDriverFragment newInstance(int position) {
        TransportOrderDriverFragment fragment = new TransportOrderDriverFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(RouterKey.TYPE, position);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_transport_order_driver, container, false);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        mMap = new HashMap();
        tabposition = getArguments().getInt(RouterKey.TYPE);
        mAdapter = new TransportOrderDriverAdapter(getContext(), null);
        viewModel = new ViewModelProvider(this).get(TransportOrderDriverViewModel.class);
        mAdapter.SetOrderListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mBinding.recyclerView.setLayoutManager(layoutManager);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        mBinding.recyclerView.setAdapter(mAdapter);
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                isLodMore = false;
                viewModel.getList(getContext(), false, mMap);
            }

            @Override
            public void onLoadMore() {
                isLodMore = true;
                viewModel.getList(getContext(), true, mMap);
            }
        });
        mAdapter.setOnItemClick(new AdapterOnItemClick<MyOrderEntity>() {
            @Override
            public void onItemClick(MyOrderEntity MyOrderEntity, int position) {
                ActivityJump.jumpToActivity(getContext(), TransportOrderDetailOwnerActivity.class, Pair.create("no", MyOrderEntity.getOrderNo()),
                        Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.CAR_OWNER));
            }
        });
        viewModel.myOrderEntity.observe(this, this::showList);

        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LogisticsEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_REFRESH_TRANSPORT_ORDER_LIST) {
            refreshData(tabposition);
        }
    }

    @Override
    protected void onLazyLoad() {
        isLodMore = false;
        viewModel.getList(getContext(), false, mMap);
    }


    /**
     * 显示数据
     *
     * @param list 数据
     */
    public void showList(List<MyOrderEntity> list) {
        mBinding.recyclerView.refreshComplete();
        if (isLodMore) {
            if (null != list && list.size() > 0) {
                mBinding.recyclerView.loadMoreComplete();
                mAdapter.addDatas(list);
            } else {
                mBinding.recyclerView.setNoMore(true);
            }
            mBinding.recyclerView.setVisibility(View.VISIBLE);
        } else {
            mBinding.recyclerView.refreshComplete();
            if (null != list && list.size() > 0) {
                mBinding.recyclerView.setVisibility(View.VISIBLE);
                mBinding.emptyView.setVisibility(View.GONE);
                mAdapter.setDatas(list);
                mBinding.recyclerView.setLoadingMoreEnabled(true);
                mAdapter.notifyDataSetChanged();
            } else {
                mAdapter.setDatas(null);
                mBinding.recyclerView.setVisibility(View.GONE);
                mBinding.emptyView.setVisibility(View.VISIBLE);
                mBinding.recyclerView.setLoadingMoreEnabled(true);
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void btnGoClick(String s, MyOrderEntity item) {
        switch (s) {
            case "确认发车":
                //TODO 去确认发车界面
                if (!TextUtils.isEmpty(item.getMessagePrice()) && !NumberUtil.trim0(item.getMessagePrice()).equals("0")) {
                    SureStartTransportActivity.start(getContext(), item.getOrderNo(), SureStartTransportActivity.START_TRANSPORT_UN_INFOPRICE, item.getMessagePrice());
                } else {
                    SureStartTransportActivity.start(getContext(), item.getOrderNo(), SureStartTransportActivity.START_TRANSPORT);
                }
                break;
            case "收款二维码":
               /* ChoosePaymentTypeDialog choosePaymentTypeDialog = new ChoosePaymentTypeDialog(true, item.getAllFreight());
                choosePaymentTypeDialog.setDialogClickCallBack(new ChoosePaymentTypeDialog.DialogClickCallBack() {
                    @Override
                    public void onItemClick(int ids) {
                        viewModel.getPayFreight(getActivity(), item.getOrderNo());
                        viewModel.ldTradeNo.observe(getActivity(), tradeNo -> {
                            if ("".equals(tradeNo)) {
                                return;
                            }
                            PayInfoEntity paymentEntity = new PayInfoEntity();
                            paymentEntity.amount = Double.valueOf(item.getAllFreight());
                            paymentEntity.tradeNo = tradeNo;
                            if (ids == ChoosePaymentTypeDialog.PAYMENT_WEIXIN) {
                                QRcodeEntity qRcodeEntity = new QRcodeEntity();
                                qRcodeEntity.amount = paymentEntity.amount + "";
                                qRcodeEntity.orderId = paymentEntity.tradeNo;
                                qRcodeEntity.payType = "WX";
                                String json = new Gson().toJson(qRcodeEntity);
                                QrCodeActivity.start(getActivity(), json);
                            } else if (ids == ChoosePaymentTypeDialog.PAYMENT_ZHIFUBAO) {
                                QRcodeEntity qRcodeEntity = new QRcodeEntity();
                                qRcodeEntity.amount = paymentEntity.amount + "";
                                qRcodeEntity.orderId = paymentEntity.tradeNo;
                                qRcodeEntity.payType = "AL";
                                String json = new Gson().toJson(qRcodeEntity);
                                QrCodeActivity.start(getActivity(), json);
                            }
                        });
                    }
                });
                choosePaymentTypeDialog.show(getFragmentManager(), "1");*/
                setGoCapitalCenter(item);
                break;
            case "确认送达":
                SureStartTransportActivity.start(getActivity(), item.getOrderNo(), SureStartTransportActivity.ARRIVED, item.getAllFreight());
                break;

            case "支付信息费":
                toPayMsgFee(item);
                break;
        }
    }

    /**
     * 支付信息费
     */
    private void toPayMsgFee(MyOrderEntity entity) {
        if (entity != null && entity.getStatus() != null && entity.getStatus() == 0
                && entity.getPaymentEndTime() != null && entity.getPaymentEndTime() > 0) {
            if (entity.getPaymentEndTime() <= System.currentTimeMillis()) {//支付已超时
                new RoundDialog.Builder(getActivity())
                        .title("提示")
                        .content("订单已超时，无法支付。")
                        .singleBtn(true)
                        .confirm("确定")
                        .cancelable(false)
                        .confirmCallback(view -> {
                            //超时了需要删除该条订单信息
                            if (mAdapter.getDatas().remove(entity)) {
                                mAdapter.notifyDataSetChanged();
                            }
                        })
                        .show();
            } else if (!TextUtils.isEmpty(entity.getMessageOrderNo())) {//支付未超时
                PersonPayActivity.start(this.getActivity(), entity.getMessageOrderNo());
            }
        }
    }

    @Override
    public void btnOffline(MyOrderEntity entity) {
        if (entity != null && !TextUtils.isEmpty(entity.getOrderNo()) && !TextUtils.isEmpty(entity.getAllFreight()))
            OfflineCollectionConfirmActivity.start(getActivity(), entity.getOrderNo(), entity.getAllFreight());
    }

    public void refreshData(int tabPosition) {
        if (mMap == null) return;
        if (tabPosition != 0) {
            if (tabPosition == 4) {
                mMap.put("status", 6);
            } else if (tabPosition == 5) {
                mMap.put("status", 4);
            } else {
                mMap.put("status", tabPosition);
            }
        }
        isLodMore = false;
        viewModel.getList(getContext(), false, mMap);
    }

    private void setGoCapitalCenter(MyOrderEntity item) {
        viewModel.getPayFreight(getActivity(), item.getOrderNo());
        viewModel.ldTradeNo.observe(getActivity(), info -> {
            if ("".equals(info.getFreightOrderNo())) {
                return;
            }
            QRcodeEntity qRcodeEntity = new QRcodeEntity();
            qRcodeEntity.amount = info.getAmount() + "";
            qRcodeEntity.orderId = info.getFreightOrderNo();
            qRcodeEntity.payType = "WX";
            String json = new Gson().toJson(qRcodeEntity);
            QrCodeActivity.start(getActivity(), json);

        });
    }
}
